package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.CheckInMapper;
import com.zzyl.nursing.service.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import com.zzyl.util.CodeGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 入住Service业务层处理
 *
 * @author mr.luo
 * @date 2025-05-18
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private IBedService bedService;
    @Autowired
    private IElderService elderService;
    @Autowired
    private ICheckInConfigService checkInConfigService;
    @Autowired
    private IContractService contractService;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }


    /**
     * 入住申请
     *
     * @param checkInApplyDto
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void apply(CheckInApplyDto checkInApplyDto) {
        //业务复杂先梳理步骤，不要着急写  梳理完先把反复用到的信息提取成变量
        //老人信息
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        //老人身份证号
        String idCardNo = checkInElderDto.getIdCardNo();
        //老人的床位id
        Long bedId = checkInApplyDto.getCheckInConfigDto().getBedId();
        // 入住配置信息
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();
        //申请入住首先，先判断老人是否已经入
        if (this.lambdaQuery().eq(CheckIn::getIdCardNo, idCardNo).count() > 0) {
            throw new BaseException("老人已经入住,不能重复申请~");
        }
        //如果老人没有入住，则查看床位是否有空闲
        Bed bed = bedService.lambdaQuery().eq(Bed::getId, bedId).eq(Bed::getBedStatus, 0).one();
        if (bed == null) {
            throw new BaseException("目前床位已被入住，请选择其他的房间");
        }
        //如果空闲更新信息为入住中，并添加入住信息
        bed.setId(bedId);
        bed.setBedStatus(1);
        boolean b = bedService.updateById(bed);
        if (!b) {
            throw new BaseException("更新床位信息失败");
        }
        //然后再查看系统是否有老人的信息，没有则添加老人信息
        Elder elder = new Elder();
        if (elderService.lambdaQuery().eq(Elder::getIdCardNo, idCardNo).count() == 0) {
            //添加老人的信息
            BeanUtils.copyProperties(checkInElderDto, elder);
//            elder.setAge(checkInElderDto.getAge());
            //添加一些默认信息
            elder.setStatus(4);
            //新增老人信息
            elderService.save(elder);
        }
        //添加入住信息
        CheckIn checkIn = new CheckIn();
        BeanUtils.copyProperties(checkInConfigDto, checkIn);
        //添加一些必要的信息
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setBedNumber(bed.getBedNumber());
        checkIn.setStatus(0);
        //设置家属信息
        List<ElderFamilyDto> elderFamilyDtoList = checkInApplyDto.getElderFamilyDtoList();
        //转JOSN
        String json = JSONUtil.toJsonStr(elderFamilyDtoList);
        checkIn.setRemark(json);
        boolean save = this.save(checkIn);
        if (!save) {
            throw new BaseException("入住信息添加失败");
        }
        //然后添加入住配置信息
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto, checkInConfig);
        //补充一些入住配置信息
        checkInConfig.setCheckInId(checkIn.getId());
        //添加签约办理信息
        boolean save1 = checkInConfigService.save(checkInConfig);
        if (!save1) {
            throw new BaseException("入住配置信息添加失败");
        }
        //添加签约办理信息
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        //补充一些签约办理信息
        contract.setElderId(elder.getId());
        contract.setContractNumber("HT" + CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());
        //判断当前合同的状态
        LocalDateTime now = LocalDateTime.now();
        if (now.isBefore(checkInConfigDto.getStartDate())) {
            contract.setStatus(0L);
        } else if (now.isAfter(checkInConfigDto.getEndDate())) {
            contract.setStatus(2L);
        } else {
            contract.setStatus(1L);
        }
        //插入合同信息
        boolean save2 = contractService.save(contract);
        if (!save2) {
            throw new BaseException("签约办理信息添加失败");
        }
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detailById(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();

        CheckInElderVo checkInElderVo = new CheckInElderVo();
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        //获取入住信息
        CheckIn checkIn = this.getById(id);
        if (checkIn == null){
            throw new BaseException("入住信息不存在");
        }
        //获取老人id
        Long elderId = checkIn.getElderId();
        //查询老人信息
        Elder elder = elderService.getById(elderId);
        //转换成VO
        BeanUtils.copyProperties(elder, checkInElderVo);

        //获取合同信息
        Contract contract = contractService.lambdaQuery()
                .eq(Contract::getElderId, elderId).one();
        //获取入住配置信息
        CheckInConfig checkInConfig = checkInConfigService.lambdaQuery()
                .eq(CheckInConfig::getCheckInId, id).one();
        //转换成VO
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        //注意返回的是String类型，需要转换一下 ,并且这个在contract中,返回的在checkInConfigVo中
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        checkInConfigVo.setStartDate(formatter.format(contract.getStartDate()));
        checkInConfigVo.setEndDate(formatter.format(contract.getEndDate()));

        //获取家属信息
        String remark = checkIn.getRemark().trim();
        JSONUtil.toList(remark, ElderFamilyVo.class);
        List<ElderFamilyVo> list = new ArrayList<>();
        if (StrUtil.isNotBlank(checkIn.getRemark())) {
            if (remark.startsWith("[")) {
                list  = JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class);
            }
        }
        //组合信息
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        checkInDetailVo.setElderFamilyVoList(list);
        return checkInDetailVo;
    }
}
